<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action
      :disabled="fromDetail"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imgUrl" :src="imgUrl" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import { uploadFile } from "@/api/article/group";
export default {
  name: "UploadSingle",
  /**
   * imgUrl: 图片地址list
   * fromDetail: 来自查看详情
   */
  props: {
    imgUrl: String,
    fromDetail: Boolean,
  },
  data() {
    return {};
  },

  methods: {
    // 封面上传
    beforeAvatarUpload(file) {
      const type = ["image/png", "image/jpg", "image/gif"];
      const isJPG = type.includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      // const len = this.insurance.riskImgUrlList.length;
      // if (len === 5) {
      //   this.$message.error("最多可上传5张图片!");
      // } else
      if (!isJPG) {
        this.$message.error("上传图片支持jpg、png、gif格式!");
      } else if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      } else {
        const formData = new FormData();
        formData.append("file", file);
        uploadFile(formData).then((res) => {
          if (res.code === 200) {
            const url = window.globalConfig.IMAGE_API + res.data.url;
            console.log(url);
            this.insurance.riskImgUrlList.push(url);
          }
        });
        return false;
      }
      return isJPG && isLt2M;
      // const formData = new FormData();
      // formData.append("file", file);
      // uploadFile(formData).then((res) => {
      //   if (res.code === 200) {
      //     const url = window.globalConfig.IMAGE_API + res.data.url;
      //     this.$emit("update:coverUrl", url);
      //   }
      // });
      // return false;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";
</style>
